﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BlockMain_Class;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace WebApplication.Controllers
{
    public class LoginController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(string account, string password)
        {
            if (account == null || password == null)
            {
                return Content("请输入用户名和密码");
            }
            //接口调用
            var data = "account=" + account + "&pwd=" + password;
            var result = HttpHelper.PostWebRequest("http://localhost:112/login", data);
            //反序列化结果
            LoginInfo l = JsonConvert.DeserializeObject<LoginInfo>(result);
            if (l.message == "ok")
            {
                //保存
                var cookieOptions = new CookieOptions
                {
                    Expires =DateTime.Now.AddDays(7),
                };
                HttpContext.Response.Cookies.Append("user", l.Id + "_" + l.account, cookieOptions);
                //验证所属节点
                return Content("ok");

            }
            else
            {
                return Content(l.message);
            }
        }

        /// <summary>
        /// 处理登录节点
        /// </summary>
        /// <returns></returns>
        public ActionResult LoginTo()
        {
            //获取cookie
            string value = "";
            HttpContext.Request.Cookies.TryGetValue("user", out value);
            //获取登录信息
            var user = GetUser.GetUserInfo(value);
            if (user != null)
            {
                return Redirect("/Public/index");
            }
            return Content("未找到节点");

        }

        public ActionResult LoginOut()
        {
            //删除cookie
            HttpContext.Response.Cookies.Delete("user");
            return Redirect("/Login");
        }
    }
}